package com.bootcamp.s3_1013.database._1018_transaction;

import com.bootcamp.s3_1013.database.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @program: myClassCode
 * @description: A transfer some money to B
 * @author: Keyu Li
 * @create: 2021-10-18 14:26
 **/

public class Demo3_transfer {
    public static void main(String[] args) {
        String success = transfer("李易", "李大耳", 20) ? "success!" : "fail!";
        System.out.println(success);
    }


    public static boolean transfer(String from, String to, Integer age) {
        Connection connection = JDBCUtils.getConnection();
        try {
            connection.setAutoCommit(false);
            try {
                PreparedStatement preparedStatement = connection.prepareStatement("update student2 set age=age-? where name=? and age>=?");
                preparedStatement.setInt(1, age);
                preparedStatement.setString(2, from);
                preparedStatement.setInt(3, age);
                int result = preparedStatement.executeUpdate();
                if (result <= 0) {
                    return false;
                }
            } catch (SQLException throwables) {
                connection.rollback();
                throwables.printStackTrace();
                return false;
            }

            int b=0;
            int a = 10/b;

            try {
                PreparedStatement preparedStatement = connection.prepareStatement("update student2 set age=age+? where name=?");
                preparedStatement.setInt(1, age);
                preparedStatement.setString(2, to);
                int result = preparedStatement.executeUpdate();
                if (result <= 0) {
                    connection.rollback();
                    return false;
                }
                connection.commit();
            } catch (SQLException throwables) {
                connection.rollback();
                throwables.printStackTrace();
                return false;
            }
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            return false;
        }
        return true;
    }
}
